#include <cstdio>
#include <csignal>
#include <io.h>
#include <direct.h>
#include "../class/ga.h"

const char FILENAME[] = "./data/";
const int CELL_NUM = 100;
const int EDGE_NUM = 200;

bool stop = false;
Ga *ga;

void signalHandler(int signum) {
    printf("stopping...\n");
    stop = true;
}

int main() {
    signal(SIGINT, signalHandler);
    srand((unsigned)time(NULL));
    if (_access(FILENAME, 0) == -1) {
        _mkdir(FILENAME);
        ga = new Ga(CELL_NUM, EDGE_NUM);
        char tmp[30];
        sprintf(tmp, "%s/0.csv", FILENAME);
        FILE *fp = fopen(tmp, "a");
        fprintf(fp, "t,avg_score,high_score,low_score,high_score_game_time,high_score_ann_time\n");
        fclose(fp);
    } else {
        ga = new Ga(FILENAME);
    }
    while(1) {
        if (ga->t % 100 == 0) {
            ga->saveAllParam(FILENAME);
            printf("saved\n");
        }
        ga->next();
        printf("t:%d  avg_score:%f  high_score:%f  low_score:%f  high_score_game_time:%f  high_score_ann_time:%f\n",
            ga->t, ga->getAvgScore(), ga->snakes[0]->score, ga->snakes[ga->snakes.size()-1]->score,
            ga->snakes[0]->game_time, ga->snakes[0]->ann_time);
        char tmp[30];
        sprintf(tmp, "%s/0.csv", FILENAME);
        FILE *fp = fopen(tmp, "a");
        fprintf(fp, "%d,%f,%f,%f,%f,%f\n",
            ga->t, ga->getAvgScore(), ga->snakes[0]->score, ga->snakes[ga->snakes.size()-1]->score,
            ga->snakes[0]->game_time, ga->snakes[0]->ann_time);
        fclose(fp);
        if (stop)
            break;
    }
    ga->saveAllParam(FILENAME);
    printf("saved\n");
    delete ga;
    return 0;
}